<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>详情页</title>
  <link rel="stylesheet" href="https://unpkg.com/mdui@2/mdui.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <script src="https://unpkg.com/showdown/dist/showdown.min.js"></script>
  <script defer src="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.js"></script>
  <script defer src="https://cdn.jsdelivr.net/npm/katex/dist/contrib/auto-render.min.js"
      onload="renderMathInElement(document.body, {
          delimiters: [
              { left: '$$', right: '$$', display: true },
              { left: '$', right: '$', display: false },
              { left: '\\(', right: '\\)', display: false }
          ]
      });"></script>
  <style>
    body { margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f0f8ff; color: #000; }
    .mdui-appbar { background-color: #007bff; color: white; border-bottom: 2px solid #0056b3; }
    .mdui-toolbar { display: flex; justify-content: space-between; align-items: center; }
    .content { padding: 20px; background-color: white; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); margin-top: 60px; }
    .title { font-size: 24px; font-weight: bold; color: #007bff; margin-bottom: 10px; }
    .category { font-size: 16px; color: #0056b3; margin-bottom: 20px; }
    .markdown-content { margin-bottom: 20px; }
    .tags { display: flex; flex-wrap: wrap; gap: 10px; }
    .tag { background-color: #e0f7fa; color: #007bff; padding: 5px 10px; border-radius: 5px; font-size: 14px; }
    .mdui-btn-search { background-color: #007bff; color: white; border-radius: 4px; margin-left: 10px; padding: 10px 20px; }
    .mdui-btn-search:hover { background-color: #0056b3; }
    .error-message { color: red; text-align: center; padding: 20px; }

    .mdui-btn-icon .mdui-icon {
      color: white;
    }
    .mdui-btn-icon:hover {
      background-color: rgba(255, 255, 255, 0.1);
      transition: background-color 0.3s ease;
    }
    .mdui-btn-icon {
      margin-right: 4px;
    }
</style>
</head>
<body>
  <div class="mdui-appbar mdui-appbar-fixed">
    <div class="mdui-toolbar">
      <button class="mdui-btn mdui-btn-icon" onclick="goBack()">
        <i class="mdui-icon material-icons">arrow_back</i>
      </button>
      <div class="mdui-toolbar-spacer"></div>
    </div>
  </div>

  <div class="content" id="content">
    <div class="error-message" id="errorMessage"></div>
    <div class="title"><input type="text" name="" id="articleTitle" style="width:max-content"></div>
    <div class="category" id="articleCategory"></div>
    <div class="markdown-origin">
      <input type="text" name="" id="markdown-origin">
    </div>
    <div class="tags" id="tags"></div>
    <div class="buttons"><button id="confirm-update">确认</button> <button id="cancel-update">取消</button></div>
  </div>

  <script src="https://unpkg.com/mdui@2/mdui.global.js"></script>
  <script>
    function goBack() {
      window.history.back();
    }

    // URL ID
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');
    
    // 错误
    function showError(message) {
      mdui.snackbar({
          message: message,
          position: 'right-top',
          timeout: 3000
        });
    }

    // 初始化
    if (!id) {
      showError('无效的文章ID');
    } else {
      fetch(`/detailData?id=${id}`)
        .then(response => {
          if (!response.ok) throw new Error('网络响应异常');
          return response.json();
        })
        .then(data => {
          if (data.error_code == 1){
            showError("文章不存在")
          }
          // 更新
          document.title = data.title;
          document.getElementById('articleTitle').value = data.title;
          document.getElementById('articleCategory').textContent = `分类：${data.category}`;
          document.getElementById('markdown-origin').value = data.content

          const tagsContainer = document.getElementById('tags');
          if (data.tags && data.tags.trim()) {
            data.tags.split(' ').forEach(tag => {
              const tagElement = document.createElement('div');
              tagElement.className = 'tag';
              tagElement.textContent = tag;
              tagsContainer.appendChild(tagElement);
            });
          } else {
            tagsContainer.innerHTML = '<div>暂无标签</div>';
          }
        })
        .catch(error => {
          showError('加载失败，请稍后重试');
          console.error('加载数据失败:', error);
        });

        submitBtn = document.getElementById('confirm-update')
        submitBtn.onclick = function(){
          const formData = {
            id: id,
            title: document.getElementById('articleTitle').value,
            content: document.getElementById('markdown-origin').value,
          };

          fetch('/api/submit', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
          })
          .then(response => response.json())
          .then(data => {
          if (data.error_code == 1){
            alert("错误：" + data.message)
          }
          else{
            alert('表单提交成功！');
            window.location.href = "/"
            }
          })
        .catch(error => {
          console.error('Error:', error);
          });
        }
    }
  </script>
</body>
</html>